package com.saturday.web.filter;

import com.saturday.common.constants.CommonConsts;
import com.saturday.common.constants.ResultConsts;
import com.saturday.common.model.HeaderContext;
import com.saturday.common.support.HeaderContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 * 前后端交互信息封装，主要为产品编码、模块编码及日志追踪号
 */
@Slf4j
@Component
public class HeaderContextFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("HeaderContextFilter初始化，name={}", filterConfig.getFilterName());
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String traceId = UUID.randomUUID().toString().replaceAll("-", "");
        MDC.put(CommonConsts.TRACE_ID_LOG, traceId);

        long startTime = System.currentTimeMillis();

        HeaderContext headerContext = new HeaderContext();
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String source = request.getHeader("source");
        String productCode = request.getHeader(ResultConsts.PRODUCT_CODE);
        if (StringUtils.isBlank(productCode)) {
            // 未指定产品
            productCode = "00";
        }
        headerContext.setTraceId(traceId);
        headerContext.setSource(source);
        HeaderContextHolder.set(headerContext);
        filterChain.doFilter(servletRequest, servletResponse);

        HeaderContextHolder.clear();
        long endTime = System.currentTimeMillis();
        log.debug("接口调用时间：{}毫秒", (endTime - startTime));
        MDC.clear();
    }

    @Override
    public void destroy() {

    }
}
